package u.hnx.admin.security.config;

import lombok.RequiredArgsConstructor;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import u.hnx.admin.security.core.AuthorizationManagerCustomizer;
import u.hnx.admin.security.core.SecurityProperties;
import u.hnx.admin.security.filter.JwtAuthenticationFilter;
import u.hnx.admin.security.filter.LoginFilter;
import u.hnx.admin.security.handler.AuthenticationExceptionCustomizer;

import java.util.Arrays;
import java.util.Collections;

@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
@EnableMethodSecurity(securedEnabled = true)
@EnableConfigurationProperties(SecurityProperties.class)
public class SecurityConfig {
    private final SecurityProperties securityProperties;
    /**
     * 自定义Web安全配置。
     *
     * 根据安全配置属性决定是否对某些API路径进行安全忽略。如果配置了开放API的路径，
     * 则这些路径将不会进行Spring Security的安全检查，允许匿名访问。
     *
     * @return WebSecurityCustomizer 实例，用于配置Spring Security的行为。
     */
    @Bean
    public WebSecurityCustomizer webSecurityCustomizer() {
        String[] openApi = securityProperties.getOpenApi();
        if(null == openApi || openApi.length == 0){
            return web -> {};
        }
        return web -> web.ignoring().requestMatchers(openApi);
    }
    @Bean
    public LoginFilter loginFilter(AuthenticationManager authenticationManager, AuthenticationFailureHandler authenticationFailureHandler, AuthenticationSuccessHandler authenticationSuccessHandler) throws Exception {
        LoginFilter loginFilter = new LoginFilter();
        loginFilter.setAuthenticationFailureHandler(authenticationFailureHandler);
        loginFilter.setAuthenticationSuccessHandler(authenticationSuccessHandler);
        loginFilter.setAuthenticationManager(authenticationManager);
        loginFilter.setFilterProcessesUrl(securityProperties.getProcessesUrl());
        return loginFilter;
    }
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder(securityProperties.getPasswordEncoderLength());
    }
    @Bean
    AuthenticationManager authenticationManager(UserDetailsService userDetailsService, PasswordEncoder passwordEncoder) {
        DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
        daoAuthenticationProvider.setUserDetailsService(userDetailsService);
        daoAuthenticationProvider.setPasswordEncoder(passwordEncoder);
        return new ProviderManager(daoAuthenticationProvider);
    }
    private CorsConfigurationSource corsConfigSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedHeaders(Collections.singletonList("*"));
        configuration.setAllowedOrigins(Collections.singletonList("*"));
        configuration.setAllowedMethods(Arrays.asList("GET", "POST"));
        configuration.setMaxAge(3600L);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http, LoginFilter loginFilter, JwtAuthenticationFilter jwtAuthenticationFilter, AuthenticationExceptionCustomizer authenticationEntryPoint, AccessDeniedHandler accessDeniedHandler, AuthorizationManagerCustomizer authorizationManagerCustomizer) throws Exception {
        http.csrf(cs -> cs.disable()).cors(cors -> cors.configurationSource(corsConfigSource()))
                .sessionManagement(httpSecuritySessionManagementConfigurer -> httpSecuritySessionManagementConfigurer.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                .headers(httpSecurityHeadersConfigurer -> httpSecurityHeadersConfigurer.cacheControl(cacheControlConfig -> cacheControlConfig.disable()).frameOptions(frameOptionsConfig -> frameOptionsConfig.disable()))
                .authorizeHttpRequests(auth -> auth.requestMatchers(securityProperties.getProcessesUrl()).permitAll().anyRequest().access(authorizationManagerCustomizer))
                // 自定义异常
                .exceptionHandling(exceptions -> exceptions
                        // 未登录或Token失效
                        .authenticationEntryPoint(authenticationEntryPoint)
                        // 访问接口没有权限
                        .accessDeniedHandler(accessDeniedHandler)).logout(AbstractHttpConfigurer::disable).formLogin(AbstractHttpConfigurer::disable);
        http.addFilterBefore(loginFilter, UsernamePasswordAuthenticationFilter.class);
        http.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
        return http.build();
    }
}
